package com.nodecollege.cloud.common.utils;

import com.nodecollege.cloud.common.enums.UpmsErrEnum;
import com.nodecollege.cloud.common.exception.UpmsException;
import com.nodecollege.cloud.common.model.RSA;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Cipher;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

/**
 * <p>
 * RSA公钥/私钥/签名工具包
 * </p>
 * <p>
 * 字符串格式的密钥在未在特殊说明情况下都为BASE64编码格式<br/>
 * 由于非对称加密速度极其缓慢，一般文件不使用它来加密而是使用对称加密，<br/>
 * 非对称加密算法可以用来对对称加密的密钥加密，这样保证密钥的安全也就保证了数据的安全
 * </p>
 *
 * @version 1.0
 * @date 2012-4-26
 */
public class RSAUtils {

    private static final Logger logger = LoggerFactory.getLogger(RSAUtils.class);

    /**
     * 加密算法RSA
     */
    public static final String KEY_ALGORITHM = "RSA";

    /**
     * 签名算法
     */
    public static final String SIGNATURE_ALGORITHM = "MD5withRSA";

    /**
     * 获取公钥的key
     */
    private static final String PUBLIC_KEY = "RSAPublicKey";

    /**
     * 获取私钥的key
     */
    private static final String PRIVATE_KEY = "RSAPrivateKey";

    /**
     * RSA最大加密明文大小
     */
    private static final int MAX_ENCRYPT_BLOCK = 117;

    /**
     * RSA最大解密密文大小
     */
    private static final int MAX_DECRYPT_BLOCK = 128;

    /**
     * <p>
     * 生成密钥对(公钥和私钥)
     * </p>
     *
     * @return
     * @throws Exception
     */
    public static RSA getKeyPair() {
        KeyPairGenerator keyPairGen = null;
        RSA rsa = new RSA();
        try {
            keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);
            keyPairGen.initialize(1024);
            KeyPair keyPair = keyPairGen.generateKeyPair();
            rsa.setPublicKey((RSAPublicKey) keyPair.getPublic());
            rsa.setPrivateKey((RSAPrivateKey) keyPair.getPrivate());
        } catch (NoSuchAlgorithmException e) {
            logger.error(UpmsErrEnum.GET_KEY_PAIR_ERROR.getMessage(), e);
            throw new UpmsException(UpmsErrEnum.GET_KEY_PAIR_ERROR);
        }
        return rsa;
    }

    /**
     * <p>
     * 公钥加密
     * </p>
     *
     * @param data      源数据
     * @param publicKey 公钥(BASE64编码)
     * @return
     * @throws Exception
     */
    public static byte[] encryptByPublicKey(byte[] data, String publicKey) {
        byte[] keyBytes = Base64Utils.decode(publicKey);
        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte[] encryptedData = null;
        try {
            KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
            Key publicK = keyFactory.generatePublic(x509KeySpec);
            // 对数据加密
            Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
            cipher.init(Cipher.ENCRYPT_MODE, publicK);
            int inputLen = data.length;
            int offSet = 0;
            byte[] cache;
            int i = 0;
            // 对数据分段加密
            while (inputLen - offSet > 0) {
                if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
                    cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);
                } else {
                    cache = cipher.doFinal(data, offSet, inputLen - offSet);
                }
                out.write(cache, 0, cache.length);
                i++;
                offSet = i * MAX_ENCRYPT_BLOCK;
            }
            encryptedData = out.toByteArray();
            out.close();
        } catch (Exception e) {
            logger.error(UpmsErrEnum.DECRYPT_BY_PUBLIC_KEY_ERROR.getMessage(), e);
            throw new UpmsException(UpmsErrEnum.DECRYPT_BY_PUBLIC_KEY_ERROR);
        } finally {
            try {
                out.close();
            } catch (IOException e) {
                logger.error(UpmsErrEnum.IO_ERROR.getMessage(), e);
                throw new UpmsException(UpmsErrEnum.IO_ERROR);
            }
        }

        return encryptedData;
    }

    /**
     * <P>
     * 私钥解密
     * </p>
     *
     * @param encryptedData 已加密数据
     * @param privateKey    私钥(BASE64编码)
     * @return
     * @throws Exception
     */
    public static byte[] decryptByPrivateKey(byte[] encryptedData, String privateKey) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte[] decryptedData = null;
        try {
            KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
            PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(Base64Utils.decode(privateKey));
            Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
            cipher.init(Cipher.DECRYPT_MODE, keyFactory.generatePrivate(pkcs8KeySpec));

            int offSet = 0;
            byte[] cache;
            int i = 0;
            // 对数据分段解密
            int inputLen = encryptedData.length;
            while (inputLen - offSet > 0) {
                if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
                    cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK);
                } else {
                    cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);
                }
                out.write(cache, 0, cache.length);
                i++;
                offSet = i * MAX_DECRYPT_BLOCK;
            }
            decryptedData = out.toByteArray();
            out.close();
        } catch (Exception e) {
            logger.error(UpmsErrEnum.DECRYPT_BY_PRIVATE_KEY_ERROR.getMessage(), e);
            throw new UpmsException(UpmsErrEnum.DECRYPT_BY_PRIVATE_KEY_ERROR);
        } finally {
            try {
                out.close();
            } catch (IOException e) {
                logger.error(UpmsErrEnum.IO_ERROR.getMessage(), e);
                throw new UpmsException(UpmsErrEnum.IO_ERROR);
            }
        }
        return decryptedData;
    }


    /**
     * <p>
     * 私钥加密
     * </p>
     *
     * @param data       源数据
     * @param privateKey 私钥(BASE64编码)
     * @return
     * @throws Exception
     */
    public static byte[] encryptByPrivateKey(byte[] data, String privateKey) {
        byte[] keyBytes = Base64Utils.decode(privateKey);
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte[] encryptedData = out.toByteArray();
        try {
            KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
            Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);
            Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
            cipher.init(Cipher.ENCRYPT_MODE, privateK);
            int inputLen = data.length;
            int offSet = 0;
            byte[] cache;
            int i = 0;
            // 对数据分段加密
            while (inputLen - offSet > 0) {
                if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
                    cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);
                } else {
                    cache = cipher.doFinal(data, offSet, inputLen - offSet);
                }
                out.write(cache, 0, cache.length);
                i++;
                offSet = i * MAX_ENCRYPT_BLOCK;
            }
            encryptedData = out.toByteArray();
            out.close();
        } catch (Exception e) {
            logger.error(UpmsErrEnum.ENCRYPT_BY_PRIVATE_KEY_ERROR.getMessage(), e);
            throw new UpmsException(UpmsErrEnum.ENCRYPT_BY_PRIVATE_KEY_ERROR);
        } finally {
            try {
                out.close();
            } catch (IOException e) {
                logger.error(UpmsErrEnum.IO_ERROR.getMessage(), e);
                throw new UpmsException(UpmsErrEnum.IO_ERROR);
            }
        }
        return encryptedData;
    }

    /**
     * <p>
     * 公钥解密
     * </p>
     *
     * @param encryptedData 已加密数据
     * @param publicKey     公钥(BASE64编码)
     * @return
     * @throws Exception
     */
    public static byte[] decryptByPublicKey(byte[] encryptedData, String publicKey) {
        byte[] keyBytes = Base64Utils.decode(publicKey);
        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte[] decryptedData = null;
        try {
            KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
            Key publicK = keyFactory.generatePublic(x509KeySpec);
            Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
            cipher.init(Cipher.DECRYPT_MODE, publicK);
            int inputLen = encryptedData.length;

            int offSet = 0;
            byte[] cache;
            int i = 0;
            // 对数据分段解密
            while (inputLen - offSet > 0) {
                if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
                    cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK);
                } else {
                    cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);
                }
                out.write(cache, 0, cache.length);
                i++;
                offSet = i * MAX_DECRYPT_BLOCK;
            }
            decryptedData = out.toByteArray();
            out.close();
        } catch (Exception e) {
            logger.error(UpmsErrEnum.DECRYPT_BY_PUBLIC_KEY_ERROR.getMessage(), e);
            throw new UpmsException(UpmsErrEnum.DECRYPT_BY_PUBLIC_KEY_ERROR);
        } finally {
            try {
                out.close();
            } catch (IOException e) {
                logger.error(UpmsErrEnum.IO_ERROR.getMessage(), e);
                throw new UpmsException(UpmsErrEnum.IO_ERROR);
            }
        }
        return decryptedData;
    }

    /**
     * <p>
     * 用私钥对信息生成数字签名
     * </p>
     *
     * @param data       已加密数据
     * @param privateKey 私钥(BASE64编码)
     * @return
     * @throws Exception
     */
    public static String sign(byte[] data, String privateKey) {
        String sign = "";
        try {
            KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
            PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(Base64Utils.decode(privateKey));
            PrivateKey privateK = keyFactory.generatePrivate(pkcs8KeySpec);
            Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
            signature.initSign(privateK);
            signature.update(data);
            sign = Base64Utils.encode(signature.sign());
        } catch (Exception e) {
            logger.error(UpmsErrEnum.SIGN_ERROR.getMessage(), e);
            throw new UpmsException(UpmsErrEnum.SIGN_ERROR);
        }
        return sign;
    }

    /**
     * <p>
     * 校验数字签名
     * </p>
     *
     * @param data      已加密数据
     * @param publicKey 公钥(BASE64编码)
     * @param sign      数字签名
     * @return
     * @throws Exception
     */
    public static boolean verify(byte[] data, String publicKey, String sign) {
        boolean verify = false;
        try {
            KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
            X509EncodedKeySpec keySpec = new X509EncodedKeySpec(Base64Utils.decode(publicKey));
            PublicKey publicK = keyFactory.generatePublic(keySpec);
            Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
            signature.initVerify(publicK);
            signature.update(data);
            verify = signature.verify(Base64Utils.decode(sign));
        } catch (Exception e) {
            logger.error(UpmsErrEnum.VERIFY_ERROR.getMessage(), e);
            throw new UpmsException(UpmsErrEnum.VERIFY_ERROR);
        }
        return verify;
    }

    public static void main(String[] args) {
        // 获取密钥
        RSA rsa = RSAUtils.getKeyPair();
        String password = "123456";
        System.out.println("明文密码：" + password);
        byte[] pass = password.getBytes();

        // 公钥加密
        byte[] gyjm = rsa.encryptByPublicKey(pass);
        String gyjmmw = org.springframework.util.Base64Utils.encodeToString(gyjm);
        System.out.println("公钥加密后的密码：" + gyjmmw);
        // 私钥解密
        byte[] syjm = rsa.decryptByPrivateKey(org.springframework.util.Base64Utils.decodeFromString(gyjmmw));
        System.out.println("私钥解密后的密码：" + new String(syjm));

        // 私钥加密
        byte[] syjiam = rsa.encryptByPrivateKey(pass);
        String syjiammw = org.springframework.util.Base64Utils.encodeToString(syjiam);
        System.out.println("私钥加密后的密码：" + syjiammw);
        // 公钥解密
        byte[] gyjiem = rsa.decryptByPublicKey(org.springframework.util.Base64Utils.decodeFromString(syjiammw));
        System.out.println("公钥解密后的密码：" + new String(gyjiem));

        // 私钥签名
        byte[] signData = syjm;
        String sign = rsa.sign(signData);
        System.out.println("私钥签名后的签名：" + sign);
        // 公钥签名认证
        boolean verify = rsa.verify(signData, sign);
        System.out.println("公钥验证签名结果：" + verify);

    }
}